package mapred.util;

public class Bytes {

    public static double Bytes2Double(byte[] bs) {
        long ret = 0;
        for (int i = 0; i < bs.length; ++i) {
            ret = ret << 8;
            ret = ret | (bs[i] & 0xFF);
        }
        return Double.longBitsToDouble(ret);
    }

    public static byte[] Double2Bytes(double d) {
        return Long2Bytes(Double.doubleToLongBits(d));
    }

    public static int Bytes2Integer(byte[] bs) {
        int ret = 0;
        for (int i = 0; i < bs.length; ++i) {
            ret = ret << 8;
            ret = ret | (bs[i] & 0xFF);
        }
        return ret;
    }

    public static byte[] Integer2Bytes(int l) {
        byte[] ret = new byte[4];
        for (int i = ret.length - 1; i >= 0; --i) {
            ret[i] = (byte) (l & 0xFF);
            l = l >> 8;
        }
        return ret;
    }

    public static long Bytes2Long(byte[] bs) {
        long ret = 0;
        for (int i = 0; i < bs.length; ++i) {
            ret = ret << 8;
            ret = ret | (bs[i] & 0xFF);
        }
        return ret;
    }

    public static byte[] Long2Bytes(long l) {
        byte[] ret = new byte[8];
        for (int i = ret.length - 1; i >= 0; --i) {
            ret[i] = (byte) (l & 0xFF);
            l = l >> 8;
        }
        return ret;
    }

    public static byte[] concat(byte[]... bss) {
        int len = 0;
        for (byte[] bs : bss) {
            len += bs.length;
        }
        byte[] ret = new byte[len];
        int i = 0;
        for (byte[] bs : bss) {
            for (int j = 0; j < bs.length; ++j) {
                ret[i] = bs[j];
                i++;
            }
        }
        return ret;
    }

    private static final String HEX = "0123456789abcdef";

    public static String Bytes2Hex(byte[] bs) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bs) {
            int i = (b >= 0 ? b : 256 + b);
            sb.append(HEX.charAt(i / 16));
            sb.append(HEX.charAt(i % 16));
        }
        return sb.toString();
    }

    public static byte[] Hex2Bytes(String hex) {
        int len = hex.length();
        if (len % 2 != 0) {
            hex = "0" + hex;
            len++;
        }

        byte[] ret = new byte[len / 2];
        for (int i = 0; i < ret.length; ++i) {
            ret[i] = Byte.parseByte(hex.substring(i * 2, i * 2 + 2), 16);
        }
        return ret;
    }

}
